<script lang="ts" setup>
import type { AttriButesType } from '../../types';
import { $t } from '@vben/locales';
import { useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import {
  Button,
  Card,
  Dropdown,
  Input,
  Menu,
  MenuItem,
  message,
  Popconfirm,
  Tooltip,
  Textarea
} from 'ant-design-vue';
import Draggable from 'vuedraggable';

import {
  deleteArticleAttributes,
  postArticleAttributes,
  postArticleAttributesListOrder,
  putArticleAttributes,
} from '#/api/portal/articleAttributes';
import {
  deleteArticleAttributesGroups,
  postArticleAttributesGroups,
  putArticleAttributesGroups,
} from '#/api/portal/articleAttributesGroups';
import { getModules } from '#/api/portal/modules';
import Icon from '#/components/Icons';

import AttributeModalView from './AttributesFormModal.vue';
import GroupFormModalView from './GroupFormModal.vue';
import SpecFormModalView from './SpecFormModal.vue';

// 类型定义
interface Attribute {
  id?: number | string;
  name: string;
  value: string;
  options?: any[];
}

interface Group {
  id?: number | string;
  name: string;
  type: AttriButesType;
  attributes: Attribute[];
}

// 状态管理
const state: {
  dragging: boolean;
  enabled: boolean;
  groups: Group[];
  modules: any[];
  post_id: number;
  specs: any[];
  type: AttriButesType;
} = reactive({
  enabled: true,
  dragging: false,
  groups: [],
  specs: [],
  post_id: 0,
  modules: [],
  type: 'parameter',
});
// 模态框配置
const [Drawer, DrawerApi] = useVbenDrawer({
  onConfirm() {
    DrawerApi.setData({
      specs: state.specs,
    });
    DrawerApi.close();
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) return;
    const drawerData = DrawerApi.getData();
    state.groups = drawerData.groups;
    state.post_id = drawerData.post_id;
    state.specs = drawerData.specs;
    state.type = drawerData.type;
    const {
      data: { list },
    } = await getModules({ attributes: 1, type: state.type });
    state.modules = list;
  },
});

// 拖拽排序
const onDragEnd = async (group_index: number) => {
  if (state.post_id > 0) {
    const group = state.groups[group_index];
    if (!group) return;
    const attributes: any = group.attributes ?? [];
    const result: { [key: string]: number } = {};
    // 使用 forEach 替代 reduce
    attributes.forEach((item: any, index: number) => {
      result[item.id] = index;
    });
    await postArticleAttributesListOrder({ list_orders: result });
  }
  state.dragging = false;
};

// 删除参数
const handleDeleteAttribute = async (
  group_index: number,
  attribute_index: number,
  attribute: Attribute,
) => {
  try {
    if (attribute?.id) {
      await deleteArticleAttributes(attribute.id as number);
    }
    state.groups[group_index]?.attributes.splice(attribute_index, 1);
  } catch {
    message.error('删除参数失败');
  }
};

// 分组模态框
const [GroupModal, GroupModalApi] = useVbenModal({
  connectedComponent: GroupFormModalView,
  closeOnClickModal: false,
  closeOnPressEscape: false,
  async onClosed() {
    const modalData = GroupModalApi.getData();
    const groupIndex = modalData.group_index;
    const group = modalData.values;
    if (modalData.isUpdata) {
      if (state.groups[groupIndex]) {
        if (group.id && state.post_id > 0) {
          await putArticleAttributesGroups(group.id, group);
        }
        state.groups[groupIndex] = {
          ...state.groups[groupIndex],
          ...group,
        };
      } else {
        if (state.post_id > 0) {
          delete group.id;
          const { data } = await postArticleAttributesGroups({
            post_id: state.post_id,
            ...group,
          });
          group.id = data.id;
        }
        state.groups.push(group);
      }
    }
  },
});

// 打开分组模态框
const handleGroup = (group?: any, group_index?: number) => {
  GroupModalApi.setState({ title: group ? '编辑分组' : '新增分组' });
  GroupModalApi.setData({
    post_id: state.post_id,
    group,
    group_index,
    group_type: state.type,
  });
  GroupModalApi.open();
};

// 删除分组
const handleDeleteGroup = async (group_index: number, group: Group) => {
  try {
    // if (
    //   state.groups[group_index]?.attributes &&
    //   state.groups[group_index]?.attributes.length > 0
    // ) {
    //   message.error('分组中还有数据,不允许删除！');
    //   return;
    // }
    if (group?.id) {
      await deleteArticleAttributesGroups(group.id as number);
    }
    state.groups.splice(group_index, 1);
  } catch {
    message.error('删除分组失败');
  }
};

// 参数模态框
const [AttributeModal, AttributeModalApi] = useVbenModal({
  connectedComponent: AttributeModalView,
  closeOnClickModal: false,
  closeOnPressEscape: false,
  async onClosed() {
    const modalData = AttributeModalApi.getData();
    const values = modalData.values;
    if (modalData.isUpdata) {
      const attribute = values.attribute;
      const attributeIndex = values.attribute_index;

      const groupIndex = values.group_index;

      if (state.groups[groupIndex] && attributeIndex >= 0) {
        if (attribute?.id) {
          await putArticleAttributes(attribute.id, attribute);
        }
        state.groups[groupIndex].attributes[attributeIndex] = attribute;
      } else {
        if (state.groups[groupIndex]?.id && state.post_id > 0) {
          const { data } = await postArticleAttributes({
            post_id: state.post_id,
            group_id: state.groups[groupIndex].id,
            ...attribute,
          });
          attribute.id = data.id;
        }
        state.groups[groupIndex]?.attributes.push(attribute);
      }
    }
  },
});

// 输入参数回车后的回调函数
const onBlurUpdateAttributeValue = async (
  group_index: number,
  attribute_index: number,
) => {
  if (!state.groups[group_index]) return;
  if (!state.groups[group_index].attributes[attribute_index]) return;
  const attribute: any = state.groups[group_index].attributes[attribute_index];
  if (state.groups[group_index] && attribute_index >= 0 && attribute?.id) {
    await putArticleAttributes(attribute.id, attribute);
  }
};

// 打开参数模态框
const handleAttribute = (
  group_index: number,
  group_type: AttriButesType,
  attribute?: Attribute,
  attribute_index?: number,
) => {
  const title = group_type === 'parameter' ? '参数' : '规格';
  AttributeModalApi.setState({
    title: attribute ? `编辑${title}` : `新增${title}`,
  });
  AttributeModalApi.setData({
    attribute,
    group_index,
    group_type,
    attribute_index,
  });

  AttributeModalApi.open();
};

// 规格模态框
const [SpecFormModal, SpecFormModalApi] = useVbenModal({
  connectedComponent: SpecFormModalView,
  closeOnClickModal: false,
  closeOnPressEscape: false,
  onClosed() {
  
    const modalData = SpecFormModalApi.getData();
    if (modalData?.value) {
          const value = cloneDeep(modalData.value);
           state.specs = value;
    }
    if (modalData?.spec) {
          const value = cloneDeep(modalData.spec);
           state.specs = value;
    }
   
  },
});



// 打开规格模态框
const handleSpec = (group_index: number) => {
  if (!state.groups[group_index]) return;

  const attributes = state.groups[group_index].attributes;

  SpecFormModalApi.setState({
    title: '规格管理',
  });
  SpecFormModalApi.setData({
    specs: state.specs,
    attributes,
    group_index,
  });

  SpecFormModalApi.open();
};

// 选择模型后的函数
const menuItemClick = async (module: any) => {
  const attributes = module?.attributes ?? [];
  if (attributes) {
    attributes.forEach((item: any) => {
      item.name = item.title; // 将 name 的值设置为 title
    });
  }
  const hasGroup = state.groups.find((item) => item.name === module.name);
  if (hasGroup) return;
  const group: Group = {
    name: module.name,
    type: module.type,
    attributes,
  };
  state.groups.push(group);
};


const isSelected = (name: string) => {
  console.log('----');
  console.log(state.groups);
  return state.groups.some(group => group.name === name);
};



</script>

<template>
  <Drawer>
    <GroupModal />
    <AttributeModal />
    <SpecFormModal />
    <div class="mb-4">
      <Button class="mb-4" type="primary" @click="handleGroup()">
        {{$t('page.common.Add Group')}}
        <span class="anticon">
          <Icon icon="ri:add-line" />
        </span>
      </Button>
      <Dropdown class="mb-4 ml-4">
        <Button type="primary" @click.prevent>
          {{$t('page.common.Select Template')}}
          <span class="anticon">
            <Icon icon="ri:arrow-drop-down-line" />
          </span>
        </Button>
        <template #overlay>
          <Menu>
            <MenuItem
              v-for="item in state.modules"
              :key="item.id"
              @click="menuItemClick(item)"
              
            >
              <span  :class="{ 'active-item': isSelected(item.name) }">{{ item.name }}</span>
            </MenuItem>
          </Menu>
        </template>
      </Dropdown>
    </div>

    <Card
      v-for="(group, key) in state.groups"
      v-show="group.type === state.type"
      :key="key"
      :bordered="false"
      class="mb-2"
    >
      <template #title>
        <span>{{ group.name }}</span>

        <Tooltip title="设置分组">
          <Button type="link" @click="handleGroup(group, key)">
            <span class="anticon">
              <Icon icon="ri:settings-5-line" />
            </span>
          </Button>
        </Tooltip>
      </template>
      <template #extra>
        <Tooltip title="设置规格：设置不同规格的价格,库存量">
          <Button
            v-if="group.type === 'spec'"
            type="link"
            @click="handleSpec(key)"
          >
            <span class="anticon">
              <Icon icon="ri:settings-5-line" />
            </span>
          </Button>
        </Tooltip>
        <Tooltip :title="`添加${group.type === 'spec' ? '规格' : '参数'}`">
          <Button type="link" @click="handleAttribute(key, group.type)">
            <span class="anticon">
              <Icon icon="ri:add-line" />
            </span>
          </Button>
        </Tooltip>

        <Popconfirm
          cancel-text="否"
          ok-text="是"
          title="确认删除分组？"
          @confirm="handleDeleteGroup(key, group)"
        >
          <Button danger type="link">
            <span class="anticon">
              <Icon icon="ri:delete-bin-line" />
            </span>
          </Button>
        </Popconfirm>
      </template>
      <Draggable
        v-model="group.attributes"
        animation="200"
        class="divide-y divide-gray-200 rounded-lg bg-white shadow"
        item-key="id"
        @end="onDragEnd(key)"
        @start="state.dragging = true"
      >
        <template #item="{ element, index }">
          <div
            :class="{ 'not-draggable': !state.enabled }"
            class="flex items-center justify-between px-4 py-3 hover:bg-gray-100"
            style="cursor: move"
          >
            <template v-if="group.type === 'spec'">
              <Tooltip>
                <template #title>
                  {{ `${element.options.join(',')}` }}
                </template>
                <span>{{ `${element.name}` }}</span>
              </Tooltip>
            </template>
            <template v-else>
              <label>{{element.name}}</label>
              <Textarea
                v-model:value="element.value"
                :addon-before="element.name"
                placeholder="请输入参数值"
                style="width: 200px"
                @press-enter="onBlurUpdateAttributeValue(key, index)"
              />
            </template>

            <div class="flex space-x-3">
              <Tooltip
                :title="`设置${group.type === 'spec' ? '规格' : '参数'}`"
              >
                <Button
                  type="link"
                  @click="handleAttribute(key, group.type, element, index)"
                >
                  <span class="anticon">
                    <Icon icon="ri:settings-5-line" />
                  </span>
                </Button>
              </Tooltip>

              <Popconfirm
                cancel-text="否"
                ok-text="是"
                title="确认删除？"
                @confirm="handleDeleteAttribute(key, index, element)"
              >
                <Button danger type="link">
                  <span class="anticon">
                    <Icon icon="ri:delete-bin-line" />
                  </span>
                </Button>
              </Popconfirm>
            </div>
          </div>
        </template>
      </Draggable>
    </Card>
  </Drawer>
</template>

<style lang="scss" scoped>
.not-draggable {
  cursor: not-allowed;
}
.active-item{
  color:#006be6
}
</style>
